package com.suixun.util.gps;

import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.suixun.util.encode.Base64;

/*
 * 通过纠偏数据库来获取百度坐标
 */
public class GpsCorrectBD {
    public static String httpGet(String url, NameValuePair[] postData) {

        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);// POST请求

        // 参数设置
        if(postData != null)
            postMethod.addParameters(postData);

        try {
            httpClient.executeMethod(postMethod);// 发送请求
            byte[] by = postMethod.getResponseBody();
            String response = new String(by);

            return response;

        } catch (HttpException e) {

            e.printStackTrace();
            return "-1";
        } catch (IOException e) {
            e.printStackTrace();
            return "-1";
        } finally {
            postMethod.releaseConnection();// 关闭连接
        }
    }


    public static Point GetFromBaidu(String lon, String lat) {
        Point pt = new Point(0, 0);
        try {
            String url = "http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=%s&y=%s";
            
            url = String.format(url, lon,lat);

            String userstr = httpGet(url, null);
            if (userstr != null && !"".equals(userstr)) {
                ObjectMapper mapper = new ObjectMapper();
                JsonNode rootNode = mapper.readTree(userstr);
                String lonstr = rootNode.path("x").asText();
                String latstr = rootNode.path("y").asText();
                lonstr = new String(Base64.decode(new String(lonstr)));
                latstr = new String(Base64.decode(new String(latstr)));
                pt.setLng((int) (Double.parseDouble(lonstr) * 1000000));
                pt.setLat((int) (Double.parseDouble(latstr) * 1000000));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pt;
    }
}
